package ebedynky.services;

import ebedynky.beans.HibernateUtil;
import ebedynky.beans.Product;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * @author davidon1
 */
public class ProductService {

    /**
     * Seesion - current connection to the db.
     */
    private Session session;

    /**
     * Constructor, retrieces the session (connection).
     */
    public ProductService() {
        this.session = HibernateUtil.getSessionFactory().openSession();
    }

    /**
     * Closes the session (connection).
     * @return success/failure.
     */
    public boolean close() {
        this.session.close();
        return !(this.session.isOpen());
    }

    /**
     * Restarts the session (connection).
     * @return success/failure.
     */
    public boolean restart() {
        this.session.close();
        if (this.session.isOpen()) {
            throw new IllegalStateException("Session could not be closed.");
        }
        this.session = HibernateUtil.getSessionFactory().openSession();
        return this.session.isOpen();
    }

    /**
     * Adds product to the db.
     * @param prd Product to be inserted
     * @return ID of the added product
     */
    public int addProduct(Product prd) {
        session.beginTransaction();
        int id = getMaxProductID() + 1;
        prd.setProductID(id);
        id = (Integer) session.save(prd);
        session.getTransaction().commit();
        return (id);
    }

    /**
     * Retrieves the maximum id currently in the database of products.
     * @return Max ID
     */
    public int getMaxProductID() {
        String hql = "select max(p.productID) from Product p";
        List list = session.createQuery(hql).list();
        if (list.get(0) != null) {
            Integer maxprdid = (Integer) list.get(0);
            return maxprdid;
        } else {
            return 0;
        }
    }

    /**
     * Retrieves a product identified by the ID.
     * @param id of the Product
     * @return Product with the ID given (null if not found)
     */
    public Product getProductByID(int id) {
        session.beginTransaction();
        Product prd = (Product) session.get(Product.class, new Integer(id));
        session.getTransaction().commit();
        return (prd);
    }

    /**
     * Retrieves a list of all products stored in the db.
     * @return List of all Products (null if no products)
     */
    public List<Product> getAllProducts() {
        session.beginTransaction();
        List<Product> prdList = session.createQuery("from Product").list();
        session.getTransaction().commit();
        return (prdList);
    }

    /**
     * Updates a specified product identified by ID.
     * @param newProduct an updated product
     */
    public void updateProduct(Product newProduct) {
        session.beginTransaction();
        Product prd = (Product) session.get(Product.class, new Integer(newProduct.getProductID()));
        prd.setName(newProduct.getName());
        prd.setOrigin(newProduct.getOrigin());
        prd.setProductCategory(newProduct.getProductCategory());
        prd.setProductGenus(newProduct.getProductGenus());
        prd.setProductSpecification(newProduct.getProductSpecification());
        prd.setProductType(newProduct.getProductType());
        prd.setOfferitems(newProduct.getOfferitems());
        prd.setVolume(newProduct.isVolume());
        prd.setWeight(newProduct.isWeight());
        prd.setProductID(newProduct.getProductID());

        session.flush();
        session.getTransaction().commit();
        session.clear();
    }

    /**
     * Removes the Product from db.
     * @param id Product ID for removal
     * @return true if successful, false otherwise
     */
    public boolean deleteProduct(int id) {
        try {
            session.beginTransaction();
            Product prd = (Product) session.get(Product.class, new Integer(id));
            session.delete(prd);
            session.getTransaction().commit();
            return (true);
        } catch (HibernateException ex) {
            return (false);
        }
    }

    /**
     * Returns a list containing products ordered by name.
     * @param name of the product to be selected
     * @return List of products, List containing product with match, null if product not found
     */
    public List<Product> getProductByName(String name) {
        session.beginTransaction();
        List<Product> prd = null;
        if (name.equals("") || name == null) {
            prd = session.createCriteria(Product.class).addOrder(Order.asc("name")).list();
        } else {
            prd = session.createCriteria(Product.class).add(Restrictions.like("name", "%" + name + "%")).addOrder(Order.asc("name")).list();
        }
        session.getTransaction().commit();
        return (prd);
    }
}
